package com.bitdf.txing.users.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.utils.PageUtils;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.common.valid.UpdateGroup;
import com.bitdf.txing.common.vo.UserInfoVo;
import com.bitdf.txing.users.ao.LoginRegistUserAo;
import com.bitdf.txing.users.entity.UserEntity;
import com.bitdf.txing.users.service.UserService;
import com.bitdf.txing.users.valid.LoginOrRegist;
import com.bitdf.txing.users.vo.UserQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 
 *
 * @author Lizhiwei
 * @email 123@qq.com
 * @date 2022-09-05 11:22:36
 */
@Slf4j
@RestController
@RequestMapping("${txing.request.path.users}")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 注册
     * @param entity
     * @return
     */
    @PostMapping("/regist")
    public R register(@Validated(value = {LoginOrRegist.class}) @RequestBody LoginRegistUserAo entity, BindingResult result){
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        if(entity.getPhone()==null || entity.getUserName()==null){
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION);
        }
        R r=userService.register(entity);
        return r;
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping("/login")
    public R login(@Validated(LoginOrRegist.class) @RequestBody LoginRegistUserAo entity, BindingResult result){
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        //1、比对密码
        UserEntity one = userService.getOne(new QueryWrapper<UserEntity>().eq("phone", entity.getPhone()).or().eq("user_name", entity.getUserName()));
        if (one==null){
            return R.error(TxCodeEnume.USER_NOT_EXIST_EXCEPTION.getCode(), TxCodeEnume.USER_NOT_EXIST_EXCEPTION.getMsg());
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(entity.getPassword(), one.getPassword());
        if (matches==false){
            return R.error(TxCodeEnume.PASSWORD_ERROR_EXCEPTION.getCode(), TxCodeEnume.PASSWORD_ERROR_EXCEPTION.getMsg());
        }
        //  2、登录
        StpUtil.login(one.getId());

        //返回所登录的用户信息（包括sessionId）
        Map<String, Object> map = new HashMap<>();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(one, userInfoVo);

        SaSession session = StpUtil.getSession(true);
        session.set("user", userInfoVo);

        map.put("user", userInfoVo);
        map.put("token", StpUtil.getTokenValue());
        log.info("登录成功");
        return R.ok().put("data", map);
    }

    /**
     * 分页查询
     */
    @SaCheckPermission("user:list")
    @RequestMapping("/list")
    @SaCheckLogin
//    @SaCheckRole("admin")
    public R list(@RequestBody UserQueryVo queryVo){
        PageUtils page = userService.queryPage(queryVo);
        return R.ok().put("data", page);
    }


    /**
     * 根据id查询用户信息
     */
    @SaCheckLogin
    @RequestMapping("/info/{id}")
    public R getUserById(@PathVariable("id") Long id){
		UserEntity user = userService.getById(id);
        if (user == null) {
            return R.error(TxCodeEnume.COMMON_TARGET_NOT_EXIST_EXCEPTION);
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user, userInfoVo);
        return R.ok().put("data", userInfoVo);
    }


    /**
     * 用户修改自身信息
     */
    @RequestMapping("/update")
    @SaCheckLogin
    public R update(@Validated(UpdateGroup.class) @RequestBody UserInfoVo userInfoVo, BindingResult result){
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        if (userInfoVo.getId() != StpUtil.getLoginIdAsLong()) {
            return R.error(TxCodeEnume.USER_NOT_PERM_EXCEPTION);
        }
        UserEntity user = new UserEntity();
        BeanUtils.copyProperties(userInfoVo, user);
        userService.updateById(user);
        log.info("用户{} 成功修改个人信息", user.getId());
        return R.ok();
    }

    /**
     * 注销账户
     */
    @SaCheckLogin
    @RequestMapping("/delete")
    public R delete(){
        // TODO 待完成
        return R.ok();
    }

    /**
     * 根据用户id集合获取用户详细信息
     * @param list
     * @return
     */
    @PostMapping("/list/ids")
    public R getByUserList(@RequestBody List<Long> list){
        List<UserInfoVo> list2 = userService.getByUserList(list);
        return R.ok().put("data", list2);
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    @SaCheckLogin
    public R loginOut(){
        log.info("用户：{} 退出登录", StpUtil.getLoginIdAsLong());
        StpUtil.logout();
        return R.ok();
    }



}
